import { getLayoutProps } from "@/common/layout/getProps";
import { PageContainer } from "@ant-design/pro-layout";
import {
  Button,
  Col,
  Form,
  Input,
  Row,
  Space,
  Upload,
  Select,
  Image,
  message
} from "antd";
import dayjs from "dayjs";
import Router from "next/router";
import { useRouter } from "next/router";
import { useState,useEffect } from "react";
import styles from "./index.module.scss";
import { http } from "@/utils/request";
import { cloneDeep } from "lodash";

export const RefereeConfirmCU = () => {
  const router = useRouter();
  const { query } = router;
  const { id, type } = query;
  const [form] = Form.useForm();
  const [userOption,setUserOption] = useState([]);
  const [currentEdit, setCurrentEdit] = useState({});
  const [personDetailData,setPersonDetailData] = useState({});

  // const isAdd = !id && !type;
  const isEdit = !!id && !type;
  const isDetail = !!id && (type === "detail");
  
  const save = async()=>{
    const values = await form.validateFields()
    const addFormData = {
      ...values,
      activityId:personDetailData.activityId,
      personName:personDetailData.name,
      isSubmit:false,
    }
    if(isEdit || isDetail){
      editSave(addFormData)
    }else{
      addSave(addFormData)
    }

  }
  const submit = async()=>{
    const values = await form.validateFields()
    console.log(personDetailData);
    const addFormData = {
      ...values,
      activityId:personDetailData.activityId,
      personName:personDetailData.name,
      isSubmit:true,
    }
    if(isEdit || isDetail){
      editSave(addFormData)
    }else{
      addSave(addFormData)
    }
  }
  //新增接口
  const addSave = async(formData:object) =>{
    try {
      const res = await http.post({
        url:'/PmExcellentPersonReq/savePmExcellentPersonReq',
        data:formData,
      })
      if(res.code == 200){
        message.success('推荐人新增成功!');
        Router.push('/employeeExcellentEvaluation/refereeConfirm');
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //编辑接口
  const editSave = async(formData:object) =>{
    try {
      const res = await http.post({
        url:'/PmExcellentPersonReq/updatePmExcellentPersonReq',
        data:{id,...formData,}
      })
      if(res.code == 200){
        message.success('推荐人修改成功!');
        Router.push('/employeeExcellentEvaluation/refereeConfirm');
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //查询所有人员
  const getUserOption = async()=>{
    try {
      const res = await http.get({
        url:'/PmPositionPerson/pmPositionPersonAll',
      })
      setUserOption(res.rows.map(item=>({value:item.baseUserId,label:item.baseUserName +'-'+item.baseUserId,name:item.baseUserName})));
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  //根据人员工号查询推荐人详细信息
  const getPersonDetail = async(id:string)=>{
    try {
      const res = await http.get({
        url:'/PmExcellentPersonReq/queryAddPmExcellentPersonReqDetail',
        params:{personName:id}
      })
      const data = cloneDeep(res.data);
      setPersonDetailData(data);
      form.setFieldsValue({
        activityName:data.activityName,
        position:data.post,
        deptName:data.dept,
        politicalStatus:data.politicsStatus,
        evaluScore:data.score,
        performanceRank:data.evaluOrder,
        personPhoto:data.photo,
      })
      setCurrentEdit(form.getFieldValue());
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  //根据id获取推荐人详情
  const getDetailById = async() => {
    try {
      const res = await http.get({
        url:'/PmExcellentPersonReq/queryPmExcellentPersonReqDetail',
        params:{personSonId:id}
      })
      const data = cloneDeep(res.data);
      console.log(data);
      form.setFieldsValue(data)
      setCurrentEdit(data);
      
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  useEffect(() => {
    if (isEdit || isDetail) {
      getDetailById();
    } else {
      form.setFieldsValue({})
    }
    getUserOption();
  }, []);

  return (
    <>
      <PageContainer header={{
        title: false
      }}>
        <div className={[styles.formCard, 'mb-[20px]'].join(' ')}>
          <Row>
            <Col span={10}>
              <Form form={form} labelAlign={'left'} initialValues={currentEdit} labelWrap labelCol={{ span: 6 }} disabled={isDetail}>
                <Form.Item
                  label={"评优活动"}
                  name="activityName"
                >
                  <Input placeholder={"请输入"} disabled></Input>
                </Form.Item>
                <Form.Item
                  label={"单据编号"}
                  name="code"
                >
                  <Input placeholder={"请输入"} disabled></Input>
                </Form.Item>
                <Form.Item
                  label={"姓名"}
                  name="personId"
                  rules={[{ required: true, message: '请选择姓名!' }]}
                >
                <Select
                  placeholder='请选择'
                  options={userOption}
                  showSearch
                  optionFilterProp="label"
                  onChange={(e)=>{
                    getPersonDetail(e);
                  }}>
                </Select>
                </Form.Item>
                <Form.Item
                  label={"岗位"}
                  name="position"
                >
                  <Input placeholder={"请输入"} disabled></Input>
                </Form.Item>
                <Form.Item
                  label={"所属部门"}
                  name="deptName"
                >
                  <Input placeholder={"请输入"} disabled></Input>
                </Form.Item>
                <Form.Item
                  label={"政治面貌"}
                  name="politicalStatus"
                >
                  <Input placeholder={"请输入"} disabled></Input>
                </Form.Item>
                <Form.Item
                  label={"绩效得分"}
                  name="evaluScore"
                >
                  <Input placeholder={"请输入"} disabled></Input>
                </Form.Item>
                <Form.Item
                  label={"绩效排名"}
                  name="performanceRank"
                >
                  <Input placeholder={"请输入"} disabled></Input>
                </Form.Item>
                <Form.Item
                  label={"本人照片"}
                  name="personPhoto"
                >
                  <Image width={200} src={currentEdit.personPhoto} />
                </Form.Item>
                <Form.Item
                  label={"季度工作业绩介绍"}
                  name="quarterlyWorkPerformance"
                  rules={[{ required: true, message: '请输入季度工作业绩介绍!' }]}
                >
                  <Input.TextArea rows={5} placeholder={"请输入"} maxLength={300} showCount></Input.TextArea>
                </Form.Item>
              </Form>
            </Col>
          </Row>

          {
            !isDetail ?
            <Row>
              <Col span={10} className={'text-right'}>
                <Space>
                  <Button onClick={()=>Router.push('/employeeExcellentEvaluation/refereeConfirm')}>返回</Button>
                  <Button type={'primary'} onClick={save}>保存</Button>
                  <Button type={'primary'} onClick={submit}>提交</Button>
                </Space>
              </Col>
            </Row>
              :
            <Row>
              <Col span={10} className={'text-right'}>
                <Space>
                  <Button onClick={() => {
                    router.back();
                  }}>返回</Button>
                </Space>
              </Col>
            </Row>
          }
        </div>
      </PageContainer>
    </>
  )
}

export const getServerSideProps = getLayoutProps;
export default RefereeConfirmCU;
